//
//  SearchTableViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/11.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "SearchTableViewController.h"
#import "SearchBarView.h"
#import "CZPopMenu.h"
#import "CZCover.h"
#import "SearchChoiceTableViewController.h"
#import <MJRefresh.h>
#import "SearchMode.h"
#import "SearchTableViewCell.h"
#import "PersonalDetailViewController.h"
#import "CompanyDetailViewController.h"
#import "MyZTTableViewController.h"
#import "RootTabViewController.h"
#import "CZTabBar.h"
#import "History.h"
#import "FXBlurView.h"
#import "ZTSearchListTableViewController.h"

@interface SearchTableViewController ()<CZCoverDelegate,ChoiceCheckedDelegate,UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>{
    NSInteger _index;
}
@property (weak, nonatomic) IBOutlet UITextField *searchtext;
@property (weak, nonatomic) IBOutlet UIButton *cancel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *changewidth;
@property (weak, nonatomic) IBOutlet UIButton *changechioce;
@property (nonatomic,strong) CAShapeLayer *btnlayer;
@property (weak, nonatomic) IBOutlet UIView *searchbar;

@property (nonatomic,strong) SearchChoiceTableViewController *choice;
@property (nonatomic,strong) NSMutableArray *datalist;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *searchitem;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftmangin;
@property (nonatomic,strong) NSMutableArray *searchcountArray;


@end

@implementation SearchTableViewController
+(instancetype)viewController{
    SearchTableViewController *search=[[SearchTableViewController alloc]init];
    search.hidesBottomBarWhenPushed=YES;
    return search;
}
-(NSMutableArray *)searchcountArray{
    if ( _searchcountArray==nil) {
        _searchcountArray=[NSMutableArray array];
    }
    return  _searchcountArray;
}
-(NSMutableArray *)datalist{
    if ( _datalist==nil) {
        _datalist=[NSMutableArray array];
    }
    return  _datalist;
}
-(void)ChoiceCeckWithIndex:(NSInteger)index{
    _index=index;
    self.searchtext.text=@"";
    [self.datalist removeAllObjects];
    [self.tableView reloadData];
}

-(SearchChoiceTableViewController *)choice{
    if (_choice==nil) {
        _choice=[[SearchChoiceTableViewController alloc]init];
        _choice.delegate=self;
    }
    return _choice;
}
-(void)ChoiceCeck:(NSString *)str{
    [self.changechioce setTitle:str forState:UIControlStateNormal];
    self.changechioce.selected=NO;
    [self rotate:self.changechioce];
}

#pragma mark - animation method
- (void)animateIndicator:(CAShapeLayer *)indicator Forward:(BOOL)forward {
    [CATransaction begin];
    [CATransaction setAnimationDuration:0.25];
    [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithControlPoints:0.4 :0.0 :0.2 :1.0]];
    
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
    anim.values = forward ? @[ @0, @(M_PI) ] : @[ @(M_PI), @0 ];
    
    if (!anim.removedOnCompletion) {
        [indicator addAnimation:anim forKey:anim.keyPath];
    } else {
        [indicator addAnimation:anim forKey:anim.keyPath];
        [indicator setValue:anim.values.lastObject forKeyPath:anim.keyPath];
    }
    
    [CATransaction commit];
    
    
}

- (CAShapeLayer *)createIndicatorWithColor:(UIColor *)color andPosition:(CGPoint)point {
    CAShapeLayer *layer = [CAShapeLayer new];
    
    UIBezierPath *path = [UIBezierPath new];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(8, 0)];
    [path addLineToPoint:CGPointMake(4, 5)];
    [path closePath];
    
    layer.path = path.CGPath;
    layer.lineWidth = 1.0;
    layer.fillColor = color.CGColor;
    
    CGPathRef bound = CGPathCreateCopyByStrokingPath(layer.path, nil, layer.lineWidth, kCGLineCapButt, kCGLineJoinMiter, layer.miterLimit);
    layer.bounds = CGPathGetBoundingBox(bound);
    
    layer.position = point;
    
    return layer;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden=YES;
    self.leftmangin.constant=40;
    [self.view layoutIfNeeded];
    [UIView animateKeyframesWithDuration:1.0 delay:0.5 options:UIViewKeyframeAnimationOptionAllowUserInteraction animations:^{
        self.leftmangin.constant=16;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
    if (self.isFromQG) {
        _index=3;
    }
    if (self.isFromZT) {
        _index=4;
    }
    if (self.isFromSearchZT) {
        _index=2;
    }
    self.searchitem.hidden=YES;
    switch (_index) {
        case 0:
            [self.datalist addObjectsFromArray:[History gethistroysbyType:@"0"]];
            break;
        case 2:
            [self.datalist addObjectsFromArray:[History gethistroysbyType:@"2"]];
            break;
        case 3:
            [self.datalist addObjectsFromArray:[History gethistroysbyType:@"3"]];
            break;
        case 4:
            [self.datalist addObjectsFromArray:[History gethistroysbyType:@"4"]];
            break;
        default:
            break;
    }
    
    if (self.datalist.count>0) {
        [self setupclearButton];
        
    }
    [self setupsearch];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (_index==0&&self.searchcountArray.count>0) {
        [XHUserDeflaut setObject:self.searchtext.text forKey:SEARCHCOND];
        [History addHistory:self.searchtext.text WithType:@"0"];
        
        [XHUserDeflaut setBool:YES forKey:ISFROMSEARCH];
        [XHUserDeflaut setBool:YES forKey:SHOWFIND];
        [self dismissViewControllerAnimated:YES completion:^{
            if ([_delegate respondsToSelector:@selector(searchCilck:WithString:)]) {
                [_delegate searchCilck:PUSHTYPECar WithString:self.searchtext.text];
            }
        }];

    }else if(_index==3&&self.searchcountArray.count>0){
        [History addHistory:self.searchtext.text WithType:@"3"];
        [self dismissViewControllerAnimated:YES completion:^{
            if ([_delegate respondsToSelector:@selector(searchCilck:WithString:)]) {
                [_delegate searchCilck:PUSHTYPEQG WithString:self.searchtext.text];
            }
        }];

       
    }else if(_index==4&&self.searchcountArray.count>0){
        [History addHistory:self.searchtext.text WithType:@"4"];
               [self dismissViewControllerAnimated:YES completion:^{
            if ([_delegate respondsToSelector:@selector(searchCilck:WithString:)]) {
                [_delegate searchCilck:PUSHTYPEZTCAR WithString:self.searchtext.text];
            }
        }];
    }else if (_index==2&&self.searchcountArray.count>0){
         [History addHistory:self.searchtext.text WithType:@"2"];
        ZTSearchListTableViewController *vc=[ZTSearchListTableViewController viewcontroller];
        vc.datalist=self.searchcountArray;
        [self.navigationController pushViewController:vc animated:YES];
        
//        [self dismissViewControllerAnimated:NO completion:nil];
    }
    
    
    else {
        [self.datalist removeAllObjects];
        self.tableView.tableFooterView=nil;
        [self.tableView reloadData];
        self.searchitem.hidden=NO;
    }
    [textField endEditing:YES];
    return YES;
    
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}
- (void)rotate:(UIButton *)sender {
    
    [self animateIndicator:self.btnlayer Forward:sender.selected];
}

-(void)setupsearch{
   
    self.searchtext.delegate=self;
    [self.cancel addTarget:self action:@selector(didcancel) forControlEvents:UIControlEventTouchUpInside];
//    if (self.ishideotherSearch||self.isFromQG) {
    if (self.isFromSearchZT) {
         self.searchtext.placeholder=@"搜索其他展厅";
    }else{
        self.searchtext.placeholder=@"可输入品牌,车型,车源类型,配置..";
    }
    
//    }
    UIView *leftview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, self.searchtext.height)];
    self.searchtext.leftView=leftview;
    self.searchtext.leftViewMode=UITextFieldViewModeAlways;
    self.searchtext.layer.cornerRadius=5;
    [self.changechioce addTarget:self action:@selector(change) forControlEvents:UIControlEventTouchUpInside];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchchange:) name:UITextFieldTextDidChangeNotification object:self.searchtext];
    self.searchbar.layer.cornerRadius=3;
//    self.btnlayer= [self createIndicatorWithColor:textnormalGary andPosition:CGPointMake(self.changechioce.width-5, self.changechioce.height/2)];
//    [self.changechioce.layer addSublayer:self.btnlayer];
    [self.searchtext becomeFirstResponder];
   
    
}

-(void)setupclearButton{
 
    UIView *clearview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, XHScreenwidth, 36)];
    
  UIButton *clearbtn =[[UIButton alloc]init];
    [clearbtn setBackgroundImage:[UIImage imageNamed:@"button_bian"] forState:UIControlStateNormal];
    [clearbtn setTitleColor:textnormalGary forState:UIControlStateNormal];
    [clearbtn setTitle:@"清空历史记录" forState:UIControlStateNormal];
    clearbtn.titleLabel.font=[UIFont systemFontOfSize:14];
    
    clearbtn.x=(XHScreenwidth-100)/2;
    clearbtn.width=100;
    clearbtn.height=36;
    [clearbtn addTarget:self action:@selector(clearbtnclick) forControlEvents:UIControlEventTouchUpInside];
    [clearview addSubview:clearbtn];
    self.tableView.tableFooterView=clearview;
    
}
-(void)clearbtnclick{
    for (History *history in self.datalist) {
        [history deleteHistory];
    }
    [self.datalist removeAllObjects];
    self.tableView.tableFooterView=nil;
    self.searchitem.hidden=NO;
    [self.tableView reloadData];
}
-(void)searchchange:(NSNotification *)notice{
    UITextField *textField=notice.object;
    
    if (textField.text.length>0) {
        if ((![textField.text isEqualToString:@"有限"]&&![textField.text isEqualToString:@"公司"]&&![textField.text isEqualToString:@"有限公"]&&![textField.text isEqualToString:@"有限公司"]&&textField.text.length>1)) {
            NSLog(@"%@",textField.text);
            NSMutableDictionary *params=[NSMutableDictionary dictionary];
           
            params[@"cond"]=textField.text;
            switch (_index) {
                case 0:
                    params[@"action"]=@"s_car";
                    params[@"s_action"]=@"count";
                    break;
                case 1:
                    params[@"action"]=@"s_shop";
                    params[@"s_action"]=@"count";
                    break;
                case 2:
                    params[@"action"]=@"s_ting";
                    params[@"s_action"]=@"count";
                    break;
                case 3:
                    params[@"action"]=@"s_buy";
                    params[@"s_action"]=@"count";
                    break;
                case 4:
                    params[@"action"]=@"tips";
//                    params[@"s_action"]=@"count";
                    break;
                default:
                    break;
            }
            
            NSString *url;
            if (_index==4) {
                url=myzturl;
                params[@"keyword"]=textField.text;
                [params addEntriesFromDictionary:self.keywords];
                
            }else{
                url=searchurl;
            }
            
            [PostUitls Post:url parameters:params success:^(id response) {
                [self.searchcountArray removeAllObjects];
                [SearchMode setupReplacedKeyFromPropertyName:^NSDictionary *{
                    return @{
                             @"ID":@"id"
                             };
                }];
                NSDictionary *dict=response;
                NSNumber *state=dict[@"state"];
                if ([state integerValue]==400) {
                NSArray *array=    [SearchMode objectArrayWithKeyValuesArray:dict[@"data"]];
                    
                    [self.searchcountArray addObjectsFromArray:array];
                    
                }
               
                
            } failure:^(NSError *error) {
                
            }];
            
        }
    }else{
        self.searchitem.hidden=YES;
        [self.datalist removeAllObjects];
        [self.datalist addObjectsFromArray:[History gethistroysbyType:[NSString stringWithFormat:@"%ld",_index]]];
        if (self.datalist.count>0) {
            [self setupclearButton];
        }
        [self.tableView reloadData];
        [self.searchcountArray removeAllObjects];
        
    }

}



-(void)change{
    CZCover *cover=[CZCover show];
    cover.delegate=self;
    CZPopMenu *menu= [CZPopMenu showInRect:CGRectMake(16, 60, 80, 144)];
    menu.contentView=self.choice.view;
    self.changechioce.selected=YES;
    [self rotate:self.changechioce];
}


-(void)didcancel{
   
    [self.searchtext endEditing:YES];
    if ([_delegate respondsToSelector:@selector(searchDidCancelClick)]) {
        [_delegate searchDidCancelClick];
    }
   [self dismissViewControllerAnimated:YES completion:^{
       
   }];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.searchtext endEditing:YES];
}

-(void)coverDidClickCover:(CZCover *)cover{
    self.changechioce.selected=NO;
    [self rotate:self.changechioce];
    [CZPopMenu hide];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    
    if (self.datalist.count==0) {
        tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    }else{
       tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;

    }
    return self.datalist.count;
}

-(void)pustocar:(History *)mode{
    [XHUserDeflaut setObject:mode.name forKey:SEARCHCOND];
    
   
    
    
    [XHUserDeflaut setBool:YES forKey:ISFROMSEARCH];
    [XHUserDeflaut setBool:YES forKey:SHOWFIND];
    
    [self dismissViewControllerAnimated:YES completion:^{
        if ([_delegate respondsToSelector:@selector(searchCilck:WithString:)]) {
            [_delegate searchCilck:PUSHTYPECar WithString:nil];
        }
    }];
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.searchtext endEditing:YES];
    History *mode=self.datalist[indexPath.row];
    switch (_index) {
        case 0:
            [self pustocar:mode];
            break;
        case 1:
            [self pustoshop:mode];
            break;

        case 2:
            [self pustoZT:mode];
            break;
        case 3:
            [self pustoQG:mode];
            break;
        case 4:
            [self pustoztcar:mode];
            break;
        default:
            break;
    }
}
-(void)pustoQG:(History *)mode{

    
    [self dismissViewControllerAnimated:YES completion:^{
        if ([_delegate respondsToSelector:@selector(searchCilck:WithString:)]) {
            [_delegate searchCilck:PUSHTYPEQG WithString:mode.name];
        }
    }];

}
-(void)pustoZT:(History *)mode{
    ZTSearchListTableViewController *lvc=[ZTSearchListTableViewController viewcontroller];
    lvc.cond=mode.name;
    [self.navigationController pushViewController:lvc animated:YES];
   
    
    
   
    
}
-(void)pustoshop:(History *)mode{
       [self dismissViewControllerAnimated:YES completion:^{
           if ([_delegate respondsToSelector:@selector(searchCilck:WithString:)]) {
               [_delegate searchCilck:PUSHTYPEShop WithString:mode.name];
           }
    }];
}
-(void)pustoztcar:(History *)mode{
    [self dismissViewControllerAnimated:YES completion:^{
        if ([_delegate respondsToSelector:@selector(searchCilck:WithString:)]) {
            [_delegate searchCilck:PUSHTYPEZTCAR WithString:mode.name];
        }
    }];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    History *mode=self.datalist[indexPath.row];
    SearchTableViewCell *cell=[SearchTableViewCell cellWithTablView:tableView];
    cell.backgroundColor=[UIColor clearColor];
    cell.name.text=mode.name;
    
    // Configure the cell...
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
